package net.maku.generator.service.impl;

import jakarta.annotation.Resource;
import net.maku.generator.config.StorageConfig;
import net.maku.generator.service.FileUploadService;
import net.maku.generator.utils.IDUtils;
import net.maku.generator.vo.UploadResourceVO;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件上传服务
 *
 * @author 阿沐 babamu@126.com
 * @since 1.0.0 2024-07-21
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Resource
    private StorageConfig storageConfig;

    /**
     *
     * @param fileType
     * @param multipartFile
     * @return
     */
    @Override
    public UploadResourceVO uploadFile(String fileType, MultipartFile multipartFile) {
        try{
            UploadResourceVO resultPath = storageConfig.generateUploadUrlPath(fileType);

            // 获取文件名
            String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename());

            // 获取文件后缀名
            String fileExtension = StringUtils.getFilenameExtension(fileName);
            String newFileName = IDUtils.generateSimpleUUID() + "." + fileExtension;
            Path filePath = Paths.get(resultPath.getRealPath(), newFileName);
            multipartFile.transferTo(filePath);

            UploadResourceVO resultVO = new UploadResourceVO()
                    .setFilePath(resultPath.getFilePath() + newFileName)
                    .setUrlPath(resultPath.getUrlPath() + newFileName);

            return resultVO;
        }catch (IOException e){
            e.printStackTrace();
            UploadResourceVO resultVO = new UploadResourceVO().setUploadResult("文件上传失败");
            return resultVO;
        }
    }

    /**
     * 获得上传文件列表
     * @return
     */
    @Override
    public List<String> getUploadedFiles() {
        List<String> files = new ArrayList<>();
        String fileUploadDir = storageConfig.getUploadDir();
        File dir = new File(fileUploadDir);
        if(dir.exists()){
            for(File file:dir.listFiles()) {
                files.add(file.getName());
            }
        }
        return files;
    }
}
